package seotools.positions.direct;

import data.DataHelper;
import data.ExtramobiNew;
import jxl.read.biff.BiffException;
import obj.Accum;
import obj.Item;
import obj.Templ;

import java.io.*;
import java.util.*;

public class AdwordsCSVAds {
    public static final String SEP = ",";
//    private static final String BASE_URL = "http://extramobi.ru/product/accumulator_";

    //    private static final int MAX_CPC = 4;
//    private static final int MAX_CPC_CONTENT = 2;
    private static Map<String, String> commonProps;
    private static final String DISP_URL = "EXTRAMOBI.RU";
    private static final String GOODS_SCHEDULE_MOSCOW_SPB = "(Monday@100%[09:00-21:30]);(Tuesday@100%[09:00-21:30]);(Wednesday@100%[09:00-21:30]);(Thursday@100%[09:00-21:30]);(Friday@100%[09:00-21:30]);(Saturday@100%[09:00-21:30]);(Sunday@100%[10:00-21:30])";
    private static final String GOODS_SCHEDULE_REGION = "(Monday@100%[00:00-24:00]);(Tuesday@100%[00:00-24:00]);(Wednesday@100%[00:00-24:00]);(Thursday@100%[00:00-24:00]);(Friday@100%[00:00-24:00]);(Saturday@100%[00:00-24:00]);(Sunday@100%[00:00-24:00])";
    private static final String REMONT_SCHEDULE = "(Monday@100%[10:00-20:00]);(Tuesday@100%[10:00-20:00]);(Wednesday@100%[10:00-20:00]);(Thursday@100%[10:00-20:00]);(Friday@100%[10:00-20:00]);(Saturday@100%[10:00-18:00]);(Sunday@100%[10:00-18:00])";
    public static final String REGION_SPB_LEN = "RU-LEN;RU-SPE";
    public static final String REGION_MOSCOW_OBL = "RU-MOS;RU-MOW";
    public static final String REGION_RUS_WITH_MILLION = "RU;-RU-LEN;-RU-MOS;-RU-MOW;-RU-SPE";
    private static final String LANG = "ru;en";

    public static final String CAMP_NAME_POSTFIX = "";

    public static void main(String[] args) throws IOException, BiffException {
        PrintStream out = new PrintStream(new FileOutputStream("direct/adwords.csv"), false, "UTF-8");
        commonProps = ExtramobiNew.readCommonProps();
        out.print(getHeader());

        Campaign campaign = getCampain(AdType.ACCUM);

        generateAds(AdRegion.SPB, 100, out, 7, 0, 100, campaign, "Nokia", "Sony Ericsson", "Motorola");
//        generateAds(AdRegion.REGION_WO_MILLION, 100, out, 4, 0, 20, campaign, "Nokia", "Sony Ericsson", "Motorola", "LG");
//        generateAds(AdRegion.MOSCOW, 100, out, 4, 0, 30, campaign, "Nokia", "Sony Ericsson", "Motorola", "LG");

//        generateAds(AdRegion.SPB, 100, out, 9, 0, 100, campaign, "Samsung", "HTC", "BlackBerry", "Apple", "Alcatel", "Siemens");
//        generateAds(AdRegion.REGION_WITH_MILLION, 100, out, 5, 0, 30, campaign, "Samsung", "HTC", "BlackBerry", "Apple", "Alcatel", "Siemens");
//        generateAds(AdRegion.MOSCOW, 100, out, 5, 0, 50, campaign, "Samsung", "HTC", "BlackBerry", "Apple", "Alcatel", "Siemens");

//        generateAccums("Nokia", false, 99, out, 7, 100);
//        generateAccums("Nokia", true, 99, out, 4, 20);
//        generateAccums("Samsung", false, 100, out, 8, 100);
//        generateAccums("Samsung", true, 100, out, 4, 20);
//        generateAccums("Motorola", false, 100, out, 6, 100);
//        generateAccums("Motorola", true, 100, out, 4, 20);
//        generateAccums("Sony Ericsson", false, 99, out, 8, 100);
//        generateAccums("Sony Ericsson", true, 99, out, 4, 20);
//        generateAccums("BlackBerry", false, 99, out, 10, 100);
//        generateAccums("BlackBerry", true, 99, out, 5, 20);
//        generateAccums("Apple", false, 100, out, 9, 100);
//        generateAccums("Apple", true, 100, out, 5, 20);
//        generateAccums("HTC", false, 99, out, 8, 100);
//        generateAccums("HTC", true, 99, out, 5, 20);
//        generateAccums("LG", false, 100, out, 7, 100);
//        generateAccums("LG", true, 100, out, 4, 20);
//
//        generateRepairs("Nokia", out, 5, 20);
//        generateRepairs("Samsung", out, 5, 20);
//        generateRepairs("Sony Ericsson", out, 5, 20);
//        generateRepairs("Motorola", out, 5, 20);
//        generateRepairs("HTC", out, 7, 50);
//        generateRepairs("Apple", out, 6, 20);
//        generateRepairs("Blackberry", out, 7, 50);
    }

    private static Campaign getCampain(AdType adType) {
        Campaign campaign = new Campaign();
        if (adType.equals(AdType.ACCUM)) {
            campaign.campaignNameSpb = "Аккумуляторы %s СПб" + CAMP_NAME_POSTFIX;
            campaign.campaignNameMoscow = "Аккумуляторы %s Москва" + CAMP_NAME_POSTFIX;
            campaign.campaignNameRegion = "Аккумуляторы %s Регионы" + CAMP_NAME_POSTFIX;
            campaign.scheduleSpb = campaign.scheduleMoscow = GOODS_SCHEDULE_MOSCOW_SPB;
            campaign.scheduleRegion = GOODS_SCHEDULE_REGION;
            campaign.stopWords = getStopWords(adType);

            Group group = new Group();
            group.headerSpb = group.headerMoscow = group.headerRegion = "Купить батарею %s СПб.";
            group.text1Spb = group.text1Moscow = group.text1Region = "Оригин-й аккумулятор %s?";
            group.text2Spb = "В наличии у м.Сенная - Скидки!";
            group.text2Moscow = "Доставка по Москве " + DirectExcelAd.SHIPPING_COST_MOSCOW + "р!";
            group.text2Region = "Доставка почтой из СПб " + DirectExcelAd.SHIPPING_COST_REGION + "р 1кл!";
            campaign.group.add(group);

//            group = new Group();
//            group.headerSpb = group.headerMoscow = group.headerRegion = "Купить аккум %s";
//            group.text1Spb = group.text1Moscow = group.text1Region = "Ориг-й аккумулятор %s";
//            group.text2Spb = "Гороховая 49. Доставка " + DirectExcelAd.SHIPPING_COST_SPB + "р!";
//            group.text2Moscow = "Пл. Ильича. Доставка " + DirectExcelAd.SHIPPING_COST_MOSCOW + "р!";
//            group.text2Region = "Доставка почтой из СПб " + DirectExcelAd.SHIPPING_COST_REGION + "р 1кл!";
//            campaign.group.add(group);

            campaign.itemPath = "data/extramobi/accum/";
            campaign.urlPostfix = "accumulator ";

            campaign.validateHeaderMap.put(".", "");
            campaign.validateHeaderMap.put(" СПб", "");
            campaign.validateHeaderMap.put(" Эриксон", "");
            campaign.validateHeaderMap.put("Сони ", "");
            campaign.validateHeaderMap.put("Моторола", "Мото");
            campaign.validateHeaderMap.put("Мото ", "");
            campaign.validateHeaderMap.put("%s ", "");

            campaign.validateTextMap.put("Оригин-й", "Ориг.");
            campaign.validateTextMap.put(" Эриксон", "");
            campaign.validateTextMap.put("Сони ", "");
            campaign.validateTextMap.put("Моторола", "Мото");
            campaign.validateTextMap.put("Мото ", "");
            campaign.validateTextMap.put("%s ", "");

            campaign.keywords.add("аккумулятор %s");
            campaign.keywords.add("батарея %s");
            campaign.keywords.add("батарейка %s");
            campaign.keywords.add("акб %s");
        }
        return campaign;
    }

    private static void printCampaignAndRegions(Campaign campaign, AdRegion region, int dailyBudget, int maxCPC, int maxCPCMedia, PrintStream out, String brandName) {
        String geo = region.regionGoogle;
        String campaignName;
        String schedule;
        String stopPhrases;
        if (region.equals(AdRegion.SPB)) {
            campaignName = campaign.campaignNameSpb;
            schedule = campaign.scheduleSpb;
        } else if (region.equals(AdRegion.MOSCOW)) {
            campaignName = campaign.campaignNameMoscow;
            schedule = campaign.scheduleMoscow;
        } else {
            campaignName = campaign.campaignNameRegion;
            schedule = campaign.scheduleRegion;
        }
        campaignName = String.format(campaignName, brandName);
        stopPhrases = getStop(campaignName, campaign.stopWords);
        out.print(getCampain(campaignName, dailyBudget, maxCPC, maxCPCMedia, LANG, geo, schedule));
        out.print(stopPhrases);
    }

    private static void printAdAndRegion(Campaign campaign, AdRegion region, int maxCPC, int maxCPCMedia, PrintStream out, String brandName, String brandNameFiltered, String name, List<String> keywords, String filteredName) {
        String campaignName;
        String header;
        String text1;
        String text2;
        String urlName = name;
        if (!name.toLowerCase().contains(brandName.toLowerCase())) {
            urlName = brandName + " " + name;
        }
        String destURL = commonProps.get("common.product-url") + DataHelper.codeInURL(campaign.urlPostfix + urlName);
        for (Group group : campaign.group) {
            if (region.equals(AdRegion.SPB)) {
                campaignName = campaign.campaignNameSpb;
                header = group.headerSpb;
                text1 = group.text1Spb;
                text2 = group.text2Spb;
            } else if (region.equals(AdRegion.MOSCOW)) {
                campaignName = campaign.campaignNameMoscow;
                header = group.headerMoscow;
                text1 = group.text1Moscow;
                text2 = group.text2Moscow;
            } else {
                campaignName = campaign.campaignNameRegion;
                header = group.headerRegion;
                text1 = group.text1Region;
                text2 = group.text2Region;
            }
            campaignName = String.format(campaignName, brandName);
            if (keywords == null) {
                name = DirectHelper.filterName(name);
                filteredName = filterNameCopyright(name);
                String[] nameParts = filteredName.split(",");
                keywords = new ArrayList<String>();
                if (nameParts.length > 1) {
                    filteredName = brandNameFiltered + " " + nameParts[0];
                    Collections.addAll(keywords, nameParts);
                } else {
                    keywords.add(name);
                }
            }
            if (filteredName != null) {
                name = filteredName;
            }
            if (!name.toLowerCase().contains(brandNameFiltered.toLowerCase())) {
                name = brandNameFiltered + " " + name;
            }
            header = String.format(header, name);
            text1 = String.format(text1, name);
            text2 = String.format(text2, name);
            header = validate(25, campaign.validateHeaderMap, header, brandName, brandNameFiltered);
            text1 = validate(32, campaign.validateTextMap, text1, brandName, brandNameFiltered);
            text2 = validate(32, campaign.validateTextMap, text2, brandName, brandNameFiltered);
            checkLength(header, text1, text2);
            System.out.println(header + "," + text1 + "," + text2 + ": " + header.length() + "," + text1.length() + "," + text2.length());
//            System.out.println(campaignName + ": " + name + ": " + header.length() + "," + text1.length() + "," + text2.length());
//        if (!brandName.equals("Apple")) {
            out.print(getGroup(campaignName, name.replaceAll("\\s", " "), maxCPC, maxCPCMedia, header, text1, text2, DISP_URL, destURL, keywords, "Broad"));
//        }
        }
    }

//    private static void generateAds(AdRegion region, int minCount, PrintStream out, int maxCPC, int maxCPCMedia, int dailyBudget, Campaign campaign, String... brands) throws IOException, BiffException {
//        List<Item> items = Item.parseItemsXlsDir(campaign.itemPath, brands);
//        for (Item item : items) {
//            if (DirectExcelAd.belongBrandsList(item.brand, brands)) {
//                generateAds(items, region, minCount, out, maxCPC, maxCPCMedia, dailyBudget, campaign);
//            }
//        }
//    }

    private static void generateAds(AdRegion region, int minCount, PrintStream out, int maxCPC, int maxCPCMedia, int dailyBudget, Campaign campaign, String... brands) throws IOException, BiffException {
        List<Item> items = Item.parseItemsXlsDir(campaign.itemPath, brands);

        for (String brandName : brands) {
            List<String> processedModels = new ArrayList<String>();
            String filteredBrand = filterNameCopyright(brandName);
            printCampaignAndRegions(campaign, region, dailyBudget, maxCPC, maxCPCMedia, out, brandName);
            for (Item item : items) {
                if (!item.brand.equalsIgnoreCase(brandName)) {
                    continue;
                }
                if (item.count < minCount) {
                    System.out.println("rejected by count: " + item.name + " < " + minCount);
                    continue;
                }
                String name = item.name.replace(item.brand + " ", "");
                printAdAndRegion(campaign, region, maxCPC, maxCPCMedia, out, brandName, filteredBrand, name, null, null);
                for (String model : item.models) {
                    String trimModel = DirectHelper.trimModel(model, brandName);
                    trimModel = filterNameCopyright(trimModel);
                    if (processedModels.contains(trimModel)) {
                        System.out.println("rejected by model : " + trimModel);
                        continue;
                    }
                    processedModels.add(trimModel);
                    String[] nameParts = trimModel.split(",");
//                    String name;
                    if (nameParts.length > 1) {
                        name = filteredBrand + " " + nameParts[0];
                    } else {
                        name = filteredBrand + " " + trimModel;
                    }
                    List<String> keywords = new ArrayList<String>();
                    if (nameParts.length > 1) {
                        for (String phrase : nameParts) {
                            addKeywords(keywords, trim(brandName + " " + phrase), campaign);
                            addKeywords(keywords, trim(filteredBrand + " " + phrase), campaign);
                        }
                    } else {
                        trimModel = brandName + " " + trimModel;
                        addKeywords(keywords, trim(trimModel), campaign);
                        trimModel = filterNameCopyright(trimModel);
                        addKeywords(keywords, trim(trimModel), campaign);
                    }
                    printAdAndRegion(campaign, region, maxCPC, maxCPCMedia, out, brandName, filteredBrand, brandName + " " + model, keywords, name);
//                out.print(getGroup(campaignName, filteredModel.replaceAll("\\,", " "), maxCPC, maxCPCMedia, header, text1, text2, DISP_URL, destURL, keywords, "Broad"));
                }
            }
        }


    }

    private static String trim(String model) {
        return model.replace("Apple ", "").replace(" Ericsson", "").replace(" Эриксон", "");
    }

    private static String validate(int maxLength, Map<String, String> validateMap, String validateString, String brandName, String brandNameFiltered) {
        for (String key : validateMap.keySet()) {
            if (validateString.length() > maxLength) {
                validateString = validateString.replace(String.format(key, brandName), validateMap.get(key));
                validateString = validateString.replace(String.format(key, brandNameFiltered), validateMap.get(key));
            } else {
                break;
            }
        }
        return validateString;
    }

    static class Campaign {
        String itemPath;
        String urlPostfix;
        String campaignNameSpb;
        String campaignNameMoscow;
        String campaignNameRegion;
        String scheduleSpb;
        String scheduleMoscow;
        String scheduleRegion;
        String[] stopWords;

        List<Group> group = new ArrayList<Group>();
        List<String> keywords = new ArrayList<String>();

        Map<String, String> validateHeaderMap = new LinkedHashMap<String, String>();
        Map<String, String> validateTextMap = new LinkedHashMap<String, String>();
    }

    static class Group {
        String headerSpb;
        String headerMoscow;
        String headerRegion;
        String text1Spb;
        String text1Moscow;
        String text1Region;
        String text2Spb;
        String text2Moscow;
        String text2Region;
    }

    private static void generateAccums(String brandName, boolean regions, int minCount, PrintStream out, int maxCPC, int dailyBudget) throws IOException {

        List<String> processedModels = new ArrayList<String>();
        int maxCPCContent = maxCPC - 2;
        String filteredBrand = filterNameCopyright(brandName);

        String campaignName = "Аккумуляторы " + filteredBrand + " СПб" + CAMP_NAME_POSTFIX;
        if (regions) {
            campaignName = "Аккумуляторы " + filteredBrand + " Регионы" + CAMP_NAME_POSTFIX;
            out.print(getCampain(campaignName, dailyBudget, maxCPC, maxCPCContent, LANG, REGION_RUS_WITH_MILLION, ""));
        } else {
            out.print(getCampain(campaignName, dailyBudget, maxCPC, maxCPCContent, GOODS_SCHEDULE_MOSCOW_SPB));
        }

        out.print(getStop(AdType.REMONT, campaignName));

        List<Accum> accums = Accum.parseAccums(brandName, 1);
        for (Accum accum : accums) {
            if (accum.count < minCount) {
                System.out.println("rejected by count: " + accum.name);
                continue;
            }
            String name = DirectHelper.filterName(accum.name);
            String filteredName = filterNameCopyright(name);
            String[] nameParts = filteredName.split(",");
            if (nameParts.length > 1) {
                filteredName = filteredBrand + " " + nameParts[0];
            }
            String header = "Аккумулятор " + filteredName;
            String text1 = "Аккумулятор " + filteredName + " " + accum.price + "руб!";
//            String text2 = "Бесплатная доставка СПб сегодня!";
            String text2 = "Самовывоз м.Восстания;дост. 190р";
            if (header.length() > 25) {
                header = header.replace(" Самсунг", "");
                header = header.replace("Моторола", "Moto");
                header = header.replace("Moto", "Mot");
                header = header.replace("Сони Эриксон", "SE");
                header = header.replace("Блэкберри", "Black.");
            }
            if (regions) {
                text2 = "Доставка почтой из СПб 190р 1кл.";
            }
            if (text1.length() > 32) {
                text1 = text1.replace("руб", "р");
            }
            if (text1.length() > 32) {
                text1 = text1.replace(" Самсунг", "");
                text1 = text1.replace("Сони Эриксон", "SE");
                text1 = text1.replace("Блэкберри", "Black-ry");
                text1 = text1.replace("Моторола", "Moto");
            }

            checkLength(header, text1, text2);
            System.out.println(header + "," + text1 + "," + text2 + ": " + header.length() + "," + text1.length() + "," + text2.length());

            List<String> keywords = new ArrayList<String>();
//            keywords.add(accum.name.replace("Nokia ", ""));
            keywords.add(accum.name.replace(brandName, "").trim());
//            keywords.add(filteredName);
//            String destURL = BASE_URL + accum.name.replaceAll("\\s", "_").toLowerCase();
            String destURL = accum.url;
            if (!accum.brandName.equals("Apple")) {
                out.print(getGroup(campaignName, filteredName.replaceAll("\\s", " "), maxCPC, maxCPCContent, header, text1, text2, DISP_URL, destURL, keywords, "Broad"));
            }
            int i = 0;
            for (String model : accum.devices) {
                String trimModel = DirectHelper.trimModel(model, brandName);
                destURL = accum.deviceURLs.get(i++);
                trimModel = filterNameCopyright(trimModel);
                if (processedModels.contains(trimModel)) {
//                    System.out.println("rejected by model : " + trimModel);
                    continue;
                }
                processedModels.add(trimModel);
                nameParts = trimModel.split(",");
                if (nameParts.length > 1) {
                    name = filteredBrand + " " + nameParts[0];
                } else {
                    name = filteredBrand + " " + trimModel;
                }

                String filteredModel = filteredBrand + " " + trimModel;
                header = "Аккумулятор " + name;
                text1 = "Аккумулятор " + name + " " + accum.price + "руб!";
                if (text1.length() > 32) {
                    text1 = text1.replace("руб", "р");
                }
                if (header.length() > 25) {
                    header = header.replace("Самсунг", "Самс.");
                    header = header.replace("Моторола", "Moto");
                    header = header.replace("Moto", "Mot");
                    header = header.replace("Сони Эриксон", "SE");
                    header = header.replace("Блэкберри", "Black.");
                    header = header.replace("Incredible", "Incredibl");
                }
                if (header.length() > 25) {
                    header = header.replace("Мото", "");
                }
                if (text1.length() > 32) {
                    text1 = text1.replace(" руб", "р");
                }
                if (text1.length() > 32) {
                    text1 = text1.replace(" Самсунг", "");
                    text1 = text1.replace("Моторола", "Moto");
                    text1 = text1.replace("Сони Эриксон", "SE");
                    text1 = text1.replace("Блэкберри", "Black-ry");
                }
                if (text1.length() > 32) {
                    text1 = text1.replace("Мото", "");
                    text1 = text1.replace("Black-ry", "Bla-ry");
                }
                checkLength(header, text1, text2);
                keywords = new ArrayList<String>();
                if (nameParts.length > 1) {
                    for (String phrase : nameParts) {
                        addAccumsKeywords(keywords, phrase);
                    }
                } else {
                    addAccumsKeywords(keywords, trimModel.replace("Айфон", "iphone"));
                }
                out.print(getGroup(campaignName, filteredModel.replaceAll("\\,", " "), maxCPC, maxCPCContent, header, text1, text2, DISP_URL, destURL, keywords, "Broad"));
            }
        }
    }

    private static void generateRepairs(String vendor, PrintStream out, int maxCPC, int dailyBudget) throws BiffException, IOException {
        List<String> processedModels = new ArrayList<String>();
        int maxCPCContent = maxCPC - 2;

        String filteredBrand = filterNameCopyright(vendor);

        String campaignName = "Ремонт " + filteredBrand + " СПб" + CAMP_NAME_POSTFIX;
        out.print(getCampain(campaignName, dailyBudget, maxCPC, maxCPCContent, REMONT_SCHEDULE));

        List<Templ> phones = Templ.parseTempls("phones", "remont", 1);

        out.print(getStop(AdType.REMONT, campaignName));

        for (Templ phone : phones) {
            if (!phone.vendor.equalsIgnoreCase(vendor)) {
                continue;
            }
            int i = 0;

            String text1 = "Профес-й ремонт любой сложности!";
            String text2 = "Центр СПб срочно качест недорого";

            List<String> models = new ArrayList<String>();

            for (String model : phone.models) {
                String trimModel = DirectHelper.trimModel(model, vendor);
                String destURL = phone.modelUrls.get(i++);
                if (processedModels.contains(trimModel) || DirectExcelAd.excludeModel(trimModel)) {
                    continue;
                }
                String filteredModel = filterNameCopyright(trimModel);

                String name;
                String[] nameParts = trimModel.split(",");
                if (nameParts.length > 1) {
                    name = filteredBrand + " " + filterNameCopyright(nameParts[0]);
                } else {
                    name = filteredBrand + " " + filteredModel;
                }

                String header = "Ремонт " + name + " СПб";
                if (header.length() > 25) {
                    header = header.replace("Самсунг", "Sams.");
                    header = header.replace("Сони Эриксон", "Сони Эрик");
                    header = header.replace("Сони Эрик", "SE");
                    header = header.replace("ThunderBolt", "ThunderBol");
                    header = header.replace("Блэкберри", "Black-ry");
                    header = header.replace("Моторола", "Moto");
                }

                checkLength(header, text1, text2);
                System.out.println(trimModel + ": " + header.length() + "," + text1.length() + "," + text2.length());

                processedModels.add(trimModel);

                if (phone.vendor.equalsIgnoreCase("sony ericsson")) {
                    phone.vendor = "SE";
                }

                List<String> keywords = new ArrayList<String>();

                if (nameParts.length > 1) {
                    for (String phrase : nameParts) {
                        addRemontKeywords(phrase, keywords);
                        models.add(phrase);
                    }
                } else {
                    addRemontKeywords(trimModel, keywords);
                    models.add(trimModel);
                }

                out.print(getGroup(campaignName, filteredModel.replaceAll("\\,", " "), maxCPC, maxCPCContent, header, text1, text2, DISP_URL, destURL, keywords, "Broad"));
            }
            String header = "Ремонт " + filteredBrand + " СПб";
            checkLength(header, text1, text2);
            System.out.println(filteredBrand + ": " + header.length() + "," + text1.length() + "," + text2.length());

            if (!vendor.equalsIgnoreCase("apple")) {
                List<String> keywords = new ArrayList<String>();
                addRemontKeywords(vendor, keywords);
                if (!(vendor.equalsIgnoreCase("htc") || vendor.equalsIgnoreCase("lg") || vendor.equalsIgnoreCase("apple"))) {
                    addRemontKeywords(DirectExcelAd.translit(vendor), keywords);
                }
                String urlPart = phone.vendor.toLowerCase().replace(" ", "-");
                out.print(getGroup(campaignName, filteredBrand, maxCPC, maxCPCContent, header, text1, text2, DISP_URL, DirectExcelAd.getRemontURL(vendor, urlPart), keywords, models, "Broad"));
            }
        }
    }

    private static void addRemontKeywords(String phrase, List<String> keywords) {
        keywords.add("ремонт " + phrase);
        keywords.add("замена " + phrase);
        keywords.add("прошивка " + phrase);
        keywords.add("прошить " + phrase);
        keywords.add("перепрошивка " + phrase);
        keywords.add("перепрошить " + phrase);
        keywords.add("разлочка " + phrase);
        keywords.add("разлочить " + phrase);
        keywords.add("разблокировать " + phrase);
        keywords.add("разблокировка " + phrase);
        keywords.add("русификация " + phrase);
        keywords.add("русифицировать " + phrase);
        keywords.add("не работает " + phrase);
    }

    private static void addKeywords(List<String> keywords, String phrase, Campaign campaign) {
        for (String keyword : campaign.keywords) {
            keyword = String.format(keyword, phrase);
            keywords.add(keyword);
        }
    }

    private static void addAccumsKeywords(List<String> keywords, String phrase) {
        keywords.add("Аккумулятор " + phrase);
        keywords.add("Батарея " + phrase);
        keywords.add("Батарейка " + phrase);
        keywords.add("АКБ " + phrase);
    }

    private static void checkLength(String header, String text1, String text2) {
        if (header.length() > 25 || text1.length() > 32 || text2.length() > 32) {
            throw new IllegalStateException(header + ";" + header.length() + "; " + text1 + ";" + text1.length() + "; " + text2 + ";" + text2.length());
        }
    }

    public static String[] getStopWords(AdType type) {
        if (type.equals(AdType.ACCUM)) {
            return DirectExcelAd.ACCUMS_STOP_PHRASES.split(" -");
        } else if (type.equals(AdType.REMONT)) {
            return DirectExcelAd.REMONT_STOP_PHRASES.split(" -");
        }
        throw new IllegalArgumentException("Unknown type " + type);
    }

    private static String filterNameCopyright(String name) {
        name = name.replace("Nokia", "Нокиа");
        name = name.replace("Samsung", "Самсунг");
        name = name.replace("Sony Ericsson", "Сони Эриксон");
        name = name.replace("HTC", "НТС");
        name = name.replace("Motorola", "Моторола");
        name = name.replace("N-Gage", "NGage");
        name = name.replace("BlackBerry", "Блэкберри");
        name = name.replace("Blackberry", "Блэкберри");
        name = name.replace("Apple", "Эпл");
        name = name.replace("iPhone", "Айфон");
        return name;
    }

//    private static String getStop(String[] stopWords, String campaignName) {
//        return getStop()
//    }

    private static String getStop(AdType type, String campaignName) {
        String[] stopWords = getStopWords(type);
        return getStop(campaignName, stopWords);
    }

    private static String getStop(String campaignName, String[] stopWords) {
        StringBuilder csv = new StringBuilder();
        for (String word : stopWords) {
            if (word.isEmpty()) continue;
            csv.append(campaignName).append(SEP).
                    append(SEP).
                    append(SEP).
                    append(SEP).
                    append(SEP).
                    append(SEP).
                    append(SEP).
                    append(SEP).
                    append(word).append(SEP).
                    append("Campaign Negative Broad").append(SEP).
                    append(SEP).
                    append(SEP).
                    append(SEP).
                    append(SEP).
                    append(SEP).
                    append("\n")
            ;
        }
        return csv.toString();
    }

    private static String getGroup(String campaign, String groupName, int maxCPC, int maxCPCContent, String header, String text1, String text2, String dispURL, String destURL, List<String> keywords, List<String> stopPhrases, String keywordType) {
        StringBuilder csv = new StringBuilder();
        csv.append(campaign).append(SEP).
                append(SEP).
                append(SEP).
                append(SEP).
                append(SEP).
                append(groupName).append(SEP).
                append(maxCPC).append(SEP).
                append(maxCPCContent).append(SEP).
                append(SEP).
                append(SEP).
                append(header).append(SEP).
                append(text1).append(SEP).
                append(text2).append(SEP).
                append(dispURL).append(SEP).
                append(destURL).
                append("\n")
        ;
        for (String keyword : keywords) {
            csv.append(campaign).append(SEP).
                    append(SEP).
                    append(SEP).
                    append(SEP).
                    append(SEP).
                    append(groupName).append(SEP).
                    append(maxCPC).append(SEP).
                    append(maxCPCContent).append(SEP).
                    append(keyword).append(SEP).
                    append(keywordType).append(SEP).
                    append(SEP).
                    append(SEP).
                    append(SEP).
                    append(SEP).
                    append("\n")
            ;
        }
        if (stopPhrases != null) {
            for (String stopPhrase : stopPhrases) {
                csv.append(campaign).append(SEP).
                        append(SEP).
                        append(SEP).
                        append(SEP).
                        append(SEP).
                        append(groupName).append(SEP).
                        append(maxCPC).append(SEP).
                        append(maxCPCContent).append(SEP).
                        append(stopPhrase).append(SEP).
                        append("Campaign Negative Broad").append(SEP).
                        append(SEP).
                        append(SEP).
                        append(SEP).
                        append(SEP).
                        append("\n")
                ;
            }
        }
        return csv.toString();
    }

    private static String getGroup(String campaign, String groupName, int maxCPC, int maxCPCContent, String header, String text1, String text2, String dispURL, String destURL, List<String> keywords, String keywordType) {
        return getGroup(campaign, groupName, maxCPC, maxCPCContent, header, text1, text2, dispURL, destURL, keywords, null, keywordType);
    }

    private static String getHeader() {
        StringBuilder csv = new StringBuilder();
        csv.append("campaign").append(SEP).
                append("campaign daily budget").append(SEP).
                append("language").append(SEP).
                append("geo targeting").append(SEP).
                append("ad schedule").append(SEP).
                append("ad group").append(SEP).
                append("max cpc").append(SEP).
                append("max content cpc").append(SEP).
                append("keyword").append(SEP).
                append("keyword type").append(SEP).
                append("headline").append(SEP).
                append("description line 1").append(SEP).
                append("description line 2").append(SEP).
                append("display url").append(SEP).
                append("destination url").
                append("\n")
        ;
        return csv.toString();
    }

    private static String getCampain(String name, int daylyBudget, int cpc, int cpcContent, String schedule) {
        return getCampain(name, daylyBudget, cpc, cpcContent, LANG, REGION_SPB_LEN, schedule);
    }

    private static String getCampain(String name, int daylyBudget, int cpc, int cpcContent, String lang, String geo, String schedule) {
        StringBuilder csv = new StringBuilder();
        csv.append(name).append(SEP).
                append(daylyBudget).append(SEP).
                append(lang).append(SEP).
                append(geo).append(SEP).
                append(schedule).append(SEP).
                append(SEP).
                append(cpc).append(SEP).
                append(cpcContent).append(SEP).
                append(SEP).
                append(SEP).
                append(SEP).
                append(SEP).
                append(SEP).
                append(SEP).
                append("\n")
        ;
        return csv.toString();
    }
}
